import path from 'path';
// import chalk from 'chalk';
import deepmerge from 'deepmerge';
import route from '../config/router';
import locales from '../config/lang';

// eslint-disable-next-line func-names
export const mergeRouter = ({
    data = route,
    parent = {},
    requiresAuth = false,
} = {}) => {
    let result = [];

    data.forEach((item) => {
        // 忽略 404 、参数路由
        if (!item || item.path === '*' || /:\w+/.test(item.path)) {
            return;
        }

        const currentPath = path.join('/', parent.path || '', item.path);

        const meta = deepmerge(parent?.meta || {}, item?.meta || {});
        // 如果要忽略授权且当前路由配置权限
        if (requiresAuth && meta.requiresAuth) {
            return;
        }

        // 如果不要渲染
        if (meta.prerender === false) {
            return;
        }

        result.push(currentPath);

        // 如果有子路由则递归处理
        if (Array.isArray(item.children) && item.children.length) {
            console.log(item.children, 'children');
            result = result.concat(mergeRouter({
                data: item.children,
                parent: {
                    meta,
                    path: currentPath,
                },
                requiresAuth,
            }));
        }
    });

    return result;
};

// eslint-disable-next-line func-names
export const mergeLangRouter = ({ router = null, requiresAuth = false, symbols = [] } = {}) => {
    const langs = locales.map((item) => item.name);

    const result = [];

    if (!router) {
        router = mergeRouter({ requiresAuth });
    }

    if (symbols && symbols.length) {
        // 处理交易页 + 交易对
        const symbolsArr = symbols.map(item => `/exchange/${item}`);

        // 处理币种介绍 + 币种
        const introductionArr = [];
        symbols.forEach((item) => {
            const res = item.replace(/_\w+$/, '');
            // eslint-disable-next-line no-unused-expressions
            introductionArr.indexOf(res) === -1 && introductionArr.push(`/introduction/${res}`);
        });

        router = router.concat(symbolsArr, introductionArr);

        // if (process.env.SITE_ENV === 'production') {
        //     console.log(chalk.yellow('交易页交易对已加入!'));
        // }
    }

    // 多语言&&单语言渲染
    if (langs.length > 1) {
        langs.forEach(lan => {
            router.forEach((url) => {
                result.push(path.join('/', lan, url));
            });
        });
    } else {
        router.forEach((url) => {
            result.push(path.join('/', url));
        });
    }

    return result;
};
